package com.ajhlp.spring_modules.rss;

import java.io.IOException;
import java.net.URL;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.fetcher.FeedFetcher;
import com.sun.syndication.fetcher.FetcherException;
import com.sun.syndication.fetcher.impl.FeedFetcherCache;
import com.sun.syndication.fetcher.impl.HashMapFeedInfoCache;
import com.sun.syndication.fetcher.impl.HttpURLFeedFetcher;
import com.sun.syndication.io.FeedException;

@Service
public class FeedAnalyser implements IFeedAnalyser {
	
	private Logger log = Logger.getLogger("rss.analyser");
	
	//rss缓存
	private FeedFetcherCache feedInfoCache = HashMapFeedInfoCache.getInstance();
	
	private FeedFetcher fetcher = new HttpURLFeedFetcher(feedInfoCache);
	
	
	/* (non-Javadoc)
	 * @see com.ajhlp.spring_modules.rss.IFeedAnalyser#getRSSDetail(java.net.URL, int, int)
	 */
	@SuppressWarnings("unchecked")
	public List<SyndEntry> getRSSDetail(URL url, int start, int limit){
		
		if(start < 0){
			start = 0;
		}
		
		int total = this.getRSSDetailTotalNum(url);
		
		log.debug("获取["+url.toString()+"]信息共["+total+"]条");
		
		if( total == 0){
			return null;
		}
		
		if(limit <= 0){
			limit = total;
		}
		
		if(start >= total){
			return null;
		}
		
		return this.analyseRSS(url).getEntries().subList(start, (start+limit) > total ? total : (start+limit));
	}
	
	/* (non-Javadoc)
	 * @see com.ajhlp.spring_modules.rss.IFeedAnalyser#getRSSDetailTotalNum(java.net.URL)
	 */
	public int getRSSDetailTotalNum(URL url){
		
		if(this.analyseRSS(url) == null){
			return 0;
		}
		
		return this.analyseRSS(url).getEntries().size();
	}
	
	/* (non-Javadoc)
	 * @see com.ajhlp.spring_modules.rss.IFeedAnalyser#analyseRSS(java.net.URL)
	 */
	public SyndFeed analyseRSS(URL url){
		
			try {
				
				SyndFeed feed = fetcher.retrieveFeed(url);
				
				log.debug("get rss success! ["+url.toString()+"]");
				
				if(feed.getEntries() != null){
					for(int i=0;i<feed.getEntries().size();i++){
						((SyndEntry)feed.getEntries().get(i)).setSource(feed);
					}
				}
				
				return feed;
				
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				log.error("RSS地址错误["+url+"]",e);
				return null;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				log.error("读取RSS["+url.toString()+"]IO错误",e);
				return null;
			} catch (FeedException e) {
				// TODO Auto-generated catch block
				log.error("读取RSS["+url.toString()+"]解析错误",e);
				return null;
			} catch (FetcherException e) {
				// TODO Auto-generated catch block
				log.error("读取RSS["+url.toString()+"]获取错误",e);
				return null;
			} 
		
	}
	
}
